package wwl.lsf.hellospringboot.easyExcel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wwl.lsf.repository.LetCodeMapper;

import java.util.*;

/**
 * 模板的读取类
 *
 * @author Jiaju Zhuang
 */
// 有个很重要的点 DemoDataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
@Slf4j
@Data
public class DemoDataListener extends AnalysisEventListener<Map<Integer, String>> {
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 3000;
    List<Map<Integer, String>> list = new ArrayList<Map<Integer, String>>();
    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private LetCodeMapper letCodeMapper;


    private StringBuilder insertSqlPartSb = new StringBuilder();
    private StringBuilder selectTableSql = new StringBuilder();
    private int columnsCount;


    @Autowired
    DemoDataListener(LetCodeMapper letCodeMapper) {
        this.letCodeMapper = letCodeMapper;
    }

    DemoDataListener() {
    }


    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        StringBuilder insertSqlPartSbEveryBatch = new StringBuilder(this.getInsertSqlPartSb().toString());
        for (int i = 0; i < list.size(); i++) {
            if (i != 0) {
                insertSqlPartSbEveryBatch.append(",");
            }
            insertSqlPartSbEveryBatch.append("(");
            for (int j = 0; j < columnsCount; j++) {
                if (list.get(i).get(j) == null) {
                    insertSqlPartSbEveryBatch.append("null");
                } else {
                    insertSqlPartSbEveryBatch.append("'");
                    insertSqlPartSbEveryBatch.append(list.get(i).get(j));
                    insertSqlPartSbEveryBatch.append("'");
                }
                if (j != columnsCount - 1) {
                    insertSqlPartSbEveryBatch.append(",");
                }
            }
            insertSqlPartSbEveryBatch.append(")");
        }
        log.info("insert语句:{}", insertSqlPartSbEveryBatch.toString());
        letCodeMapper.executeSql(insertSqlPartSbEveryBatch.toString());
        log.info("存储数据库成功！");
    }

    /**
     * 这里会一行行的返回头
     *
     * @param headMap
     * @param context
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        String tableName = "`" + context.readSheetHolder().getSheetName() + "`";
        selectTableSql.append("select * from ").append(tableName);
        columnsCount = headMap.size();
        StringBuilder sb = new StringBuilder("create table ");
        insertSqlPartSb.append("insert into");
        insertSqlPartSb.append(tableName);
        insertSqlPartSb.append("(");
        sb.append(tableName);
        sb.append("(");
        for (int i = 0; i < headMap.size(); i++) {
            sb.append("`");
            sb.append(headMap.get(i));
            sb.append("`");
            sb.append(" varchar(100) null, ");
            insertSqlPartSb.append("`");
            insertSqlPartSb.append(headMap.get(i));
            insertSqlPartSb.append("`");
            if (headMap.size() - 1 != i) {
                insertSqlPartSb.append(",");
            }
        }
        insertSqlPartSb.append(") values ");
        sb.append(" id   int auto_increment primary key )");
        log.info("建表语句:{}", sb.toString());
        try {
            letCodeMapper.executeSql(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("建表完成:{}", sb.toString());

        String a = "账户编号,平台用户编号";
        String[] split = a.split(",");
        for (int i = 0; i < split.length; i++) {
            //创建索引
            StringBuilder indexCreate = new StringBuilder();
            indexCreate.append("create index ").append(split[i])
                    .append(" on ").append(tableName).append(" (").append(split[i]).append(")");
            try {
                letCodeMapper.executeSql(indexCreate.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            log.info("创建索引完成:{}", indexCreate.toString());
        }
    }
}
